<template>
  <div class="schedule-preview">
    <div class="header">
      <el-button @click="prevWeek">上一周</el-button>
      <el-button @click="nextWeek">下一周</el-button>
      <span class="date-range">{{ weekRangeText }}</span>
      <el-button type="primary" @click="fetchAllSchedules" style="margin-left: 20px;">所有排班</el-button>
      <el-button @click="showDoctorDialog = true" style="margin-left: 10px;">医生管理</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="deptName" label="科室" width="100" />
      <el-table-column prop="doctorName" label="医生姓名" width="100" />
      <el-table-column
        v-for="(day, idx) in weekDays"
        :key="day.date"
        :label="`${day.label}(${day.date})`"
        :min-width="120"
      >
        <template #default="scope">
          <div v-if="scope.row.schedule[day.date]">
            <div v-for="(item, i) in scope.row.schedule[day.date]" :key="i">
              <el-tag :type="item.time === '上午' ? 'warning' : 'info'" size="small">{{ item.time }}</el-tag>
              <span style="margin-left: 4px;">{{ item.content }}</span>
              <el-button size="small" type="danger" @click="deleteDoctorWork(scope.row.doctorId, day.date)" style="margin-left: 4px;">删除</el-button>
            </div>
          </div>
          <div v-else>休息</div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 医生管理弹窗 -->
    <el-dialog v-model="showDoctorDialog" title="医生管理" width="60%">
      <el-table :data="doctorList" style="width: 100%">
        <el-table-column prop="docId" label="ID" width="80"/>
        <el-table-column prop="docName" label="姓名"/>
        <el-table-column prop="deptName" label="科室"/>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="editDoctor(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteDoctor(scope.row.docId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="addDoctorDialog = true" style="margin-top: 10px;">添加医生</el-button>
    </el-dialog>

    <!-- 添加/编辑医生弹窗 -->
    <el-dialog v-model="addDoctorDialog" :title="editDoctorId ? '编辑医生' : '添加医生'">
      <el-form :model="doctorForm">
        <el-form-item label="姓名">
          <el-input v-model="doctorForm.docName"/>
        </el-form-item>
        <el-form-item label="科室">
          <el-input v-model="doctorForm.deptName"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDoctorDialog = false">取消</el-button>
        <el-button type="primary" @click="saveDoctor">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// 周切换
const weekOffset = ref(0)
const weekDays = ref([])
const tableData = ref([])

// 医生管理
const showDoctorDialog = ref(false)
const doctorList = ref([])
const addDoctorDialog = ref(false)
const doctorForm = ref({ docId: '', docName: '', deptName: '' })
const editDoctorId = ref(null)

// 获取一周日期
const getWeekDays = (offset = 0) => {
  const start = dayjs().startOf('week').add(offset, 'week').add(1, 'day')
  return Array.from({ length: 7 }).map((_, i) => {
    const d = start.add(i, 'day')
    return {
      date: d.format('YYYY-MM-DD'),
      label: `星期${'一二三四五六日'[i]}`
    }
  })
}
const weekRangeText = computed(() => {
  if (!weekDays.value.length) return ''
  return `${weekDays.value[0].date} ~ ${weekDays.value[6].date}`
})

// 获取指定周排班
const fetchSchedule = async () => {
  const week = dayjs(weekDays.value[0].date).format('YYYY-ww')
  try {
    console.log('请求的周参数:', week)
    const res = await axios.get(`/api/admin/schedule/preview/${week}`)
    console.log('获取排班接口响应:', res)
    const raw = res.data
    console.log('获取排班原始数据:', raw)
    // 假设 DoctorWork 结构：{ deptName, doctorName, doctorId, day, time, content }
    const map = {}
    raw.forEach(item => {
      const key = `${item.deptName}-${item.doctorName}-${item.doctorId}`
      if (!map[key]) {
        map[key] = {
          deptName: item.deptName,
          doctorName: item.doctorName,
          doctorId: item.doctorId,
          schedule: {}
        }
      }
      if (!map[key].schedule[item.day]) map[key].schedule[item.day] = []
      map[key].schedule[item.day].push({
        time: item.time,
        content: item.content
      })
    })
    console.log('转换后的排班数据:', Object.values(map))
    tableData.value = Object.values(map)
  } catch (e) {
    console.error('获取排班错误:', e)
    ElMessage.error('获取排班失败')
  }
}

// 获取所有排班
const fetchAllSchedules = async () => {
  try {
    const res = await axios.get('/api/admin/schedule/all')
    console.log('获取所有排班接口响应:', res)
    ElMessage.success('获取所有排班成功')
    // 你可以在这里弹窗展示所有排班，或直接替换 tableData
    // 这里只做简单替换
    tableData.value = res.data
  } catch (e) {
    console.error('获取所有排班错误:', e)
    ElMessage.error('获取所有排班失败')
  }
}

// 医生管理
const fetchDoctors = async () => {
  try {
    const res = await axios.get('/api/doctor/findAll')
    console.log('获取医生列表接口响应:', res)
    doctorList.value = res.data
  } catch (e) {
    console.error('获取医生列表错误:', e)
    ElMessage.error('获取医生列表失败')
  }
}
const addDoctor = () => {
  doctorForm.value = { docId: '', docName: '', deptName: '' }
  editDoctorId.value = null
  addDoctorDialog.value = true
}
const editDoctor = (row) => {
  doctorForm.value = { ...row }
  editDoctorId.value = row.docId
  addDoctorDialog.value = true
}
const saveDoctor = async () => {
  try {
    if (editDoctorId.value) {
      await axios.post('/api/doctor/update', doctorForm.value)
      console.log('更新医生接口响应:', res)
      ElMessage.success('更新成功')
    } else {
      await axios.post('/api/doctor/add', doctorForm.value)
      console.log('添加医生接口响应:', res)
      ElMessage.success('添加成功')
    }
    addDoctorDialog.value = false
    fetchDoctors()
  } catch (e) {
    console.error('保存医生错误:', e)
    ElMessage.error('保存失败')
  }
}
const deleteDoctor = async (docId) => {
  try {
    await axios.get('/api/doctor/delete', { params: { docId } })
    console.log('删除医生接口响应:', res)
    ElMessage.success('删除成功')
    fetchDoctors()
  } catch (e) {
    console.error('删除医生错误:', e)
    ElMessage.error('删除失败')
  }
}

// 删除单个医生排班
const deleteDoctorWork = async (docId, day) => {
  try {
    await axios.get('/api/doctorWork/delete', { params: { docId, day } })
    console.log('删除医生排班接口响应:', res)
    ElMessage.success('删除排班成功')
    fetchSchedule()
  } catch (e) {
    console.error('删除排班错误:', e)
    ElMessage.error('删除排班失败')
  }
}

// 获取所有医生排班
const fetchAllDoctorWorks = async () => {
  try {
    const res = await axios.get('/api/doctorWork/findAll')
    // 你可以弹窗展示所有医生排班
    console.log(res.data)
  } catch (e) {
    ElMessage.error('获取所有医生排班失败')
  }
}

// 获取单个医生某天排班
const fetchDoctorWorkByDay = async (docId, day) => {
  try {
    const res = await axios.get('/api/doctorWork/findByDocIdAndDay', { params: { docId, day } })
    // 你可以弹窗展示
    console.log(res.data)
  } catch (e) {
    ElMessage.error('获取医生排班失败')
  }
}

// 新增/编辑医生排班
const addOrUpdateDoctorWork = async (doctorWork, isEdit = false) => {
  try {
    if (isEdit) {
      await axios.post('/api/doctorWork/update', doctorWork)
      ElMessage.success('更新排班成功')
    } else {
      await axios.post('/api/doctorWork/add', doctorWork)
      ElMessage.success('添加排班成功')
    }
    fetchSchedule()
  } catch (e) {
    ElMessage.error('保存排班失败')
  }
}

const prevWeek = () => {
  weekOffset.value--
  weekDays.value = getWeekDays(weekOffset.value)
  fetchSchedule()
}
const nextWeek = () => {
  weekOffset.value++
  weekDays.value = getWeekDays(weekOffset.value)
  fetchSchedule()
}

onMounted(() => {
  weekDays.value = getWeekDays(weekOffset.value)
  fetchSchedule()
  fetchDoctors()
})
</script>

<style scoped>
.schedule-preview {
  padding: 24px;
}
.header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}
.date-range {
  font-size: 18px;
  font-weight: bold;
  margin-left: 16px;
}
</style>